﻿using Newtonsoft.Json.Linq;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace DotNetExtensions.Core.Http
{

    public class HttpResponse
    {
        private readonly Encoding encoding = Encoding.UTF8;
        public HttpResponse()
        {
            Code = (int)System.Net.HttpStatusCode.Created;
        }

        public HttpResponse(int code, byte[] content)
        {
            Code = code;
            Content = content;
        }
        public HttpResponse(int code, byte[] content, Cookie[] cookies)
        {
            Code = code;
            Content = content;
            Cookies = cookies;
        }
        public HttpResponse(int code, byte[] content, Cookie[] cookies, System.Text.Encoding encoding)
        {
            this.encoding = encoding;
            Code = code;
            Content = content;
            Cookies = cookies;
        }
        public HttpResponse(int code, byte[] content, System.Text.Encoding encoding)
        {
            this.encoding = encoding;
            Code = code;
            Content = content;
        }

        public HttpResponse(int code, string content)
        {
            Code = code;
            if (!string.IsNullOrEmpty(content)) Content = encoding.GetBytes(content);
        }
        public HttpResponse(int code, string content, System.Text.Encoding encoding)
        {
            this.encoding = encoding;
            Code = code;
            if (!string.IsNullOrEmpty(content)) Content = encoding.GetBytes(content);
        }
        public int Code { get; set; }
        public byte[] Content { get; set; }

        // public System.Text.Encoding Encoding { get; set; }

        public Cookie[] Cookies { get; set; }

        public bool OK
        {
            get
            {
                return Code == 200;
            }
        }


        public override string ToString()
        {
            try
            {
                if (Content != null && Content.Length > 0)
                {
                    return encoding.GetString(Content);
                }

                return "response data is empty.";
            }
            catch (Exception)
            {
                throw;
            }
        }
        public string ToString(System.Text.Encoding encoding)
        {
            try
            {
                if (Content != null && Content.Length > 0)
                {
                    return encoding.GetString(Content);
                }

                return "response data is empty";
            }
            catch (Exception)
            {
                throw;
            }
        }
        public JToken ToJson()
        {
            string json = this.ToString(encoding);
            if (string.IsNullOrEmpty(json)) return JValue.CreateNull();

            return JToken.Parse(json);
        }
    }
}
